package com.loie.xcx.web.controller;

import com.alibaba.fastjson2.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.loie.xcx.comm.JsonResult;
import com.loie.xcx.model.bo.ItemBO;
import com.loie.xcx.model.dto.QRCodeDTO;
import com.loie.xcx.service.ItemService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhl
 */
@Slf4j
@RequestMapping("/QRCode")
@RestController
@AllArgsConstructor
public class QuickResponseCodeController {
    private final ItemService itemService;

    @PostMapping("/generatePicture")
    public JsonResult<String> generatePicture(@RequestParam String msg) {
        QRCodeDTO qrCodeDTO = JSONObject.parseObject(msg, QRCodeDTO.class);
        String content = qrCodeDTO.getContent();
        String recordId = qrCodeDTO.getRecordId();
        if (StringUtils.isNotBlank(content) && StringUtils.isNotBlank(recordId)) {
            // 表示是二维码
            BarcodeFormat qrCode = BarcodeFormat.QR_CODE;
            // 二维码宽度
            Integer length = qrCodeDTO.getLength();
            if (length == null) {
                length = 800;
            }
            int logoLength = (length / 3);

            ItemBO itemBO = itemService.getItemNoAndClassItemNoByRecordId(recordId);
            String itemNo = itemBO.getItemNo();
            String classItemNo = itemBO.getClassItemNo();
            try {
                Map<EncodeHintType, Object> hints = new HashMap<>(3);
                // 设置二维码编字符集
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                // 设置二维码的外间距
                hints.put(EncodeHintType.MARGIN, 2);
                // 设置二维码容错级别
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                // 创建二维码对象
                BitMatrix bitMatrix = new MultiFormatWriter().encode(content, qrCode, length, length, hints);
                // 输出二维码
                BufferedImage qrCodeImage = toBufferedImage(bitMatrix);
                // 准备画图
                Graphics2D g = qrCodeImage.createGraphics();
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("logo3.jpg");
                // 读取logo文件，计算正中央的位置，画到qrCode图片中去
                Image logoImage = ImageIO.read(resourceAsStream);
                int location = (length - logoLength) / 2;
                g.drawImage(logoImage, location, location, logoLength, logoLength, null);

                g.setColor(Color.black);
                g.setFont(new Font("仿宋", Font.BOLD, 20));
                g.drawString(itemNo, 50, length - 28);
                g.drawString(classItemNo, 50, length - 6);
                g.dispose();
                //用于输出照片文件查看
//                ImageIO.write(qrCodeImage, "png", new File("/Users/zhl/self/workspace/git/xcxAPI/src/main/resources/out.png"));
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(qrCodeImage, "png", os);
                byte[] pic = os.toByteArray();
                int ret = itemService.updateItemByQrCode(recordId, pic);
                os.close();
                if (ret == 1) {
                    return new JsonResult<>();
                }
            } catch (WriterException | IOException e) {
                throw new RuntimeException(e);
            }
        }
        return new JsonResult<>(400, "入参异常");
    }

    private BufferedImage toBufferedImage(BitMatrix matrix) {
        int black = 0xFF000000;
        int white = 0xFFFFFFFF;
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, (matrix.get(x, y) ? black : white));
            }
        }
        return image;

    }
}
